package com.nf.controller.manage;

import com.google.gson.Gson;
import com.nf.controller.BaseServlet;
import com.nf.util.FileUploadUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 编写servlet，实现影片海报的上传
 */

@MultipartConfig
@WebServlet("/api/FilmPictureUploadServlet.do")
public class FilmPictureUploadServlet extends BaseServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part=req.getPart("attach");

        //使用上传工具类来实现文件（影片海报）的上传
        FileUploadUtil fuu=new FileUploadUtil();
        // 指定上传文件的路径
        String path="E:\\workspace\\vscode\\cinema-web\\images";
        //设置允许上传文件的大小和类型
        fuu.setMaxSize(10*1024*1024);
        fuu.setAlowFileExt("jpg,png,jpeg");

        //文件上传，并返回上传的文件名
        String filename = fuu.upload(part, path) ;
        System.out.println("上传成功，上传的文件名为：" + filename+",路径为："+path);

        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        //向客户端浏览器响应一个JSON格式的字符串
        out.print(new Gson().toJson(successJson(filename)));
        out.flush();
        out.close();
    }
}
